import {getUserInfo} from '../../api/member.js';
import {editTaskContent, getTaskContentDetail} from "../../api/activity";

import Util from '../../utils/util.js';

const app = getApp();
Page({
  data: {
    batActive: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;

    this.setData({
      id: options.id || ""
    })
    if (Util.isEmpty(this.data.id)) {
      return app.Tips({title: "参数错误"}, {tab: 1, url: "../index/index"})
    }

    Util.chekWxLogin().then(res => {
      getUserInfo().then(result => {
        that.setData({
          member: result.data || {}
        })
        if (Util.isEmpty(result.data.avatar)) {
          wx.navigateTo({
            url: "../member/edit"
          });
          return;
        }
      }).catch(errmsg => {
        app.Tips({title: errmsg})
      })

      wx.showLoading({title: "正在加载..."})
      getTaskContentDetail(this.data.id).then(res => {
        let task = res.data.task || null
        task.content = Util.formatRichText(task.content)

        if (res.data.content.status != 2) {
          return app.Tips({title: "当前状态不可修改"}, {tab: 5, url: "../task/detail?id=" + task.id})
        }

        that.setData({
          task: task,
          fields: task.extends || {}
        })

        wx.hideLoading()
      }).catch(errmsg => {
        console.log(errmsg)
        app.Tips({title: errmsg})
      })
    })

    this.onLoadTabbar();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  formSubmit(e) {
    const that = this,
      fields = that.data.fields,
      form_data = e.detail.value;

    if (!this.data.batActive)
      return false;

    let msg = "";
    for (const k in fields) {
      if (fields[k].type == "file") {
        let fileIds = [];
        for (const j in fields[k].values) {
          fileIds.push(fields[k].values[j].file_id);
        }
        form_data[k] = fileIds;
        continue;
      }

      if (fields[k].type == 'pictures') {
        let picture_ids = [];

        for (const j in fields[k].values) {
          picture_ids.push(fields[k].values[j].picture_id);
        }

        if (picture_ids.length < 1) {
          msg = fields[k].title + "必填";
          break;
        }

        form_data[k] = picture_ids
        continue;
      }

      if (!form_data[k]) {
        msg = fields[k].title + "必填";
        break;
      }
    }

    if (msg) {
      return app.Tips({title: msg});
    }

    form_data['id'] = this.data.id;

    that.setData({
      batActive: false
    })
    wx.showLoading({title: "正在提交..."})
    editTaskContent(form_data).then(res => {
      that.setData({
        batActive: true
      })
      wx.setStorageSync('is_refresh', 1)
      if (res.data.status == 1) {
        return app.Tips({
          title: "提交成功",
          icon: "success"
        }, {tab: 3})
      } else {
        return app.Tips({
          title: "提交成功",
          icon: "success"
        }, {
          tab: 5,
          url: "result?task_id=" + this.data.task_id + "&integral=" + parseInt(this.data.task.integral)
        })
      }
    }).catch(errmsg => {
      that.setData({
        batActive: true
      })
      return app.Tips({title: errmsg}, {tab: 3})
    })
  },

  inputName(e) {
    let fields = this.data.fields;
    const id = e.currentTarget.id;
    fields[id].default_val = e.detail.value;
    this.setData({fields: fields});
  },

  onChooseMutiImage(e) {
    const that = this,
      key = e.currentTarget.dataset.key;

    let fields = that.data.fields,
      images = fields[key].values || [];
    let size = 6 - images.length

    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      count: size,
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;

        wx.showLoading({
          title: '正在上传',
          mask: true,
        })
        const url = `${app.globalData.url}/api/upload`; // 仅为示例，非真实的接口地址
        for (let index = 0; index < tempFilePaths.length; index++) {
          // images.push({ path_preview: tempFilePaths[index],path: tempFilePaths[index]  });
          wx.uploadFile({
            url: url,
            filePath: tempFilePaths[index],
            name: 'fileData',
            header: {
              token: wx.getStorageSync("cookie_token")
            },
            formData: {},
            success(res) {
              const data = JSON.parse(res.data);
              images.push({
                path: data.path,
                picture_id: data.id
              });

              fields[key].values = images

              that.setData({fields: fields})
              if (index + 1 == tempFilePaths.length) {
                wx.hideLoading();
              }
            }
          });
        }
      }
    });
  },

  uploadTaskFile(e) {
    const that = this,
      key = e.currentTarget.dataset.key
    let fields = that.data.fields;

    let fileIds = fields[key].values || [];
    wx.chooseMessageFile({
      count: 1,
      type: 'all',
      success(res) {
        const tempFilePaths = res.tempFiles;
        let canUpload = true;
        wx.showLoading({title: "正在上传..."})
        for (let index = 0; index < tempFilePaths.length; index++) {
          wx.uploadFile({
            url: `${app.globalData.url}/api/upload`,
            filePath: tempFilePaths[index]['path'],
            name: 'fileData',
            header: {
              'content-type': 'multipart/form-data',
              'token': wx.getStorageSync("cookie_token")
            },
            formData: {
              object_type: "file",
              file_name: tempFilePaths[0].name,
            },
            success(res) {
              const data = JSON.parse(res.data);
              fileIds.push({
                path: data.path,
                name: data.name,
                file_id: data.id
              });

              fields[key].values = fileIds
              if (index + 1 == tempFilePaths.length) {
                wx.hideLoading();
              }
              that.setData({fields: fields});
            }
          });
        }

      }
    })
  },

  removePic(e) {
    const that = this,
      fk = e.currentTarget.dataset.fk,
      index = e.currentTarget.dataset.k

    let fields = that.data.fields

    fields[fk].values.splice(index, 1)
    that.setData({fields: fields})

    return
    if (fields[fk].values[index].id) {
      deletePicture(fields[fk].values[index].picture_id)
        .then(res => {
          fields[fk].values.splice(index, 1)
          that.setData({fields: fields})
        })
        .catch(errmsg => {
          app.Tips({title: errmsg})
        })
    } else {
      fields[fk].values.splice(index, 1)
      that.setData({fields: fields})
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this;
    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({
        isIphoneX: res
      })
    });

    wx.createSelectorQuery().in(that).select('#weui-footer')
      .boundingClientRect(function (rect) {
        that.setData({
          bottom: parseInt(rect.height) + 15
        })
      }).exec()
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})